package com.example.demo.util;

import cn.hutool.core.util.RandomUtil;
import com.example.demo.sort.Sort;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * 排序校验工具类
 */
@Service
public class CheckUtil {

    /**
     * 数组长度
     */
    private static final int ARRAY_LENGTH = 50;

    /**
     * 最大数值
     */
    private static final int MAX = 100;

    /**
     * 最小值
     */
    private static final int MIN = -100;

    /**
     * 调用sort类进行排序
     * @param sort
     */
    public void run(Sort sort) {
        this.run(sort, this.getNums());
    }

    /**
     * 调用sort类进行排序
     * @param sortList
     */
    public void run(List<Sort> sortList) {
        int[] nums = this.getNums();
        for (Sort sort : sortList) {
            int[] copy = Arrays.copyOf(nums, nums.length);
            this.run(sort, copy);
        }
    }

    /**
     * 调用sort类进行排序
     * @param sort
     * @param nums
     */
    public void run(Sort sort, int[] nums) {
        System.out.println("====【" + sort.getName() + "】开始");
        this.printNums(nums);
        nums = sort.sortArray(nums);
        this.checkNums(nums);
        System.out.println("====【" + sort.getName() + "】结束");
        System.out.println();
    }

    /**
     * 获取一个待排序数组
     * @return
     */
    public int[] getNums() {
        int[] nums = new int[ARRAY_LENGTH];
        for (int i = 0; i < nums.length; i++) {
            nums[i] = RandomUtil.randomInt(MIN, MAX);
        }
        return nums;
    }

    /**
     * 打印数组
     * @param nums
     */
    public void printNums(int[] nums) {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (int num : nums) {
            if (sb.length() > 1) {
                sb.append(",");
            }
            sb.append(num);
        }
        sb.append("]");
        System.out.println(sb.toString());
    }

    /**
     * 校验排序
     * @param nums
     * @return
     */
    public boolean checkNums(int[] nums) {
        this.printNums(nums);
        int asc = 0;
        int desc = 0;
        for (int i = 0; i < nums.length - 1; i++) {
            if (nums[i] < nums[i + 1]) {
                asc++;
            } else if (nums[i] > nums[i + 1]) {
                desc++;
            } else {
                asc++;
                desc++;
            }
        }
        if (asc == nums.length - 1 && desc != nums.length - 1) {
            System.out.println("升序");
            return true;
        } else if (asc != nums.length - 1 && desc == nums.length - 1) {
            System.out.println("降序");
            return true;
        } else {
            System.out.println("无序，检测不通过");
            return false;
        }
    }

}
